package com.manster.security;

import com.manster.exception.CaptchaException;
import com.manster.util.Const;
import com.manster.util.JwtUtils;
import com.manster.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author manster
 * @Date 2022/3/14
 **/
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        //判断路径和请求方式
        if ("/login".equals(url) && request.getMethod().equals("POST")){
            try {
                //校验验证码
                validate(request);
            }catch (CaptchaException e){
                //交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        filterChain.doFilter(request, response);
    }

    //校验验证码
    private void validate(HttpServletRequest request){

        String code = request.getParameter("code");
        String token = request.getParameter("token");
        if (!StringUtils.hasText(code) || !StringUtils.hasText(token)){
            throw new CaptchaException("验证码不能为空");
        }

        if(!code.equals(redisUtils.hget(Const.CAPTCHA_KEY, token))){
            throw new CaptchaException("验证码错误");
        }

        //使用完这个验证码就删掉
        redisUtils.hdel(Const.CAPTCHA_KEY, token);
    }
}
